import serial
import sys
import os
import time
import re
import socket
import configparser


def sendData():#串口读取数据
	myPrint('Start------------------>\n')
	while True:
		pritLogName = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
		try:
			line = ser.readline()
			#myPrint('Start------------------>1\n')
			lastData = line.decode('utf-8').replace(' ','')#过滤空格
			wirteLog(lastData)#保存Log到本地
			print(pritLogName+":"+lastData)#打印Log
			#myPrint('Start------------------>2\n')
			try:
				client.send(bytes(lastData,"utf-8"))#发送数据到手机
				data = client.recv(1024).decode('utf-8')
			except socket.timeout:#防止阻塞
				continue
			except ConnectionResetError:
				continue
			if data == 'quit':
				closeData()#关闭数据流接口
				break
		except KeyboardInterrupt:
			closeData()
			
def wirteLog(log):#保存Log文件
	#with open(filePaht,'r') as readfile:
		#readfile.read()
	with open(filePaht,'a') as writefile:
		writefile.write(log+'\n')

def myPrint(str):
	a = 1
	if a==1:
		print(str)

def closeData():
	myPrint("stop---->serial")
	ser.close()#关闭
	myPrint("stop---->TCP")
	client.close()#环比	

#初始化
config = configparser.ConfigParser()
config.read("net.ini")
user_com = config.get("comUser1","user_com")
user_ip = config.get("comUser1","user_ip")
user_port =  config.get("comUser1","user_port")
filename = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
filePaht = filename + config.get("comUser1","user_log_name")#文件保存路径和命名

ser = serial.Serial(user_com, 115200, timeout=3)#初始化串口
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
try:
	print("正在尝试连接手机----")
	print("尝试连接的IP地址："+user_ip+":"+user_port)
	print("当前IP地址："+"")
	client.connect((user_ip, int(user_port)))
except TimeoutError:
	print("无法连接手机")
	pass
except ConnectionRefusedError:
	print("无法连接手机")
	pass
client.settimeout(1)#防止阻塞
sendData()#处理接收到的数据
